﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Department;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Depart
{
    public class GetDepartmentHandler : IRequestHandler<GetDepartCommand, ApiResult<List<DepartmentDto>>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepo;
        private readonly IMapper mapper;

        public GetDepartmentHandler(IBaseRepository<DepartmentModel> departRepo,IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<DepartmentDto>>> Handle(GetDepartCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartmentDto>> result = new ApiResult<List<DepartmentDto>>();
            result.Code = ApiEnums.Success;
            result.Msg = "查询部门树状列表成功!";
            result.Data = GetTree(0);//
            return Task.FromResult(result);
        }
        /// <summary>
        /// 递归查询部门树状列表
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<DepartmentDto> GetTree(long parentId)
        {
            //根据父id查找所有部门实体
            var departments = departRepo.GetAll().Where(x => x.ParentId == parentId).ToList();
            //把实体转换为需要的DTO类型
            List<DepartmentDto> dtos = mapper.Map<List<DepartmentDto>>(departments);

            foreach (var department in dtos) {
                //通过当前部门的id,找到部门下的所有海子部门,赋值给Children
                department.Children = GetTree(department.Id);
            }
            return dtos;
        }




















        ///// <summary>
        ///// 使用递归查部门的树
        ///// </summary>
        ///// <param name="parentId"></param>
        ///// <returns></returns>
        //public List<DepartmentDto> GetTree(long parentId) { 
        //    var departments  = departRepo.GetAll().Where(x => x.ParentId == parentId).ToList();//根据父id查找所有的部门
        //    var dtos = mapper.Map<List<DepartmentDto>>(departments);//把部门列表转换为Dto列表
        //    foreach (var d in dtos) {
        //        d.Children = GetTree(d.Id);//给dto里的部门children赋值
        //    }
        //    return dtos;//把dtos返回
        //}
    }
}
